package network.httpserver;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.URI;
import java.nio.channels.FileChannel;

public class FileContent implements Content{

	private static File ROOT = new File("/home/glogo/");
	private File file;
	
	private String type = null;
	
	private FileChannel fileChannel;
	private long length = -1;
	private long position = -1;
	
	public FileContent(URI uri) {
		file = new File(ROOT, uri.getPath().replace('/', File.separatorChar));
	}

	public String type(){
		if(type != null)	return type;
		String nm = file.getName();
		if(nm.endsWith(".html") || nm.endsWith(".htm"))
			type = "text/html; charset=utf-8";
		else if(nm.indexOf('.') < 0 || nm.endsWith(".txt"))
			type = "text/plain; charset=utf-8";
		else
			type = "applocation/octet-stream";
		return type;
	}
	
	@Override
	public void prepare() throws IOException {
		if(fileChannel == null){
			fileChannel = new RandomAccessFile(file, "r").getChannel();
		}
		length = fileChannel.size();
		position = 0;
	}

	@Override
	public boolean send(ChannelIO cio) throws IOException {
		if(fileChannel == null)
			throw new IllegalStateException();
		if(position < 0)
			throw new IllegalStateException();
		if(position >= length)
			return false;		//发送完毕返回false
		
		position += cio.transerTo(fileChannel, position, length - position);
		
		return (position < length);
	}

	@Override
	public void release() throws IOException {
		if(fileChannel != null){
			fileChannel.close();
			file = null;
		}
	}

	@Override
	public long length() {
		return length;
	}

}
